package com.rfs.juc;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @author renfushuai
 * @date 2022/12/30
 */
public class ForkJoinDemo extends RecursiveTask<Integer> {
    private static final int THRESHOLD = 2;
    private int start;
    private int end;

    public ForkJoinDemo(int start, int end) {
        this.start=start;
        this.end=end;
    }
    @Override
    protected Integer compute() {
        boolean canCompute=(end-start)<=THRESHOLD;
        int sum=0;
        if (canCompute) {
            for (int i = start; i <= end; i++) {
                sum+=i;
            }
            return sum;
        }
        int middle=(start+end)/2;
        ForkJoinDemo leftTask = new ForkJoinDemo(start, middle);
        ForkJoinDemo rightTask = new ForkJoinDemo(middle + 1, end);
        leftTask.fork();
        rightTask.fork();
        Integer leftResult = leftTask.join();
        Integer rightResult = rightTask.join();
        sum=rightResult+leftResult;
        return sum;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinDemo task = new ForkJoinDemo(1, 100);
        ForkJoinTask<Integer> submit = forkJoinPool.submit(task);
        Integer result = submit.get();
        System.out.println(result);
    }
}
